#include "SeqList.h"

void SLInit(SL* pc)
{
    pc->a = (SLDataType*)malloc(sizeof(SLDataType) * INIT_CAPACITY);
    if (NULL == pc->a)
    {
        perror("malloc fail");
        return;
    }
    pc->size = 0;
    pc->capacity = INIT_CAPACITY;
}

void SLDestroy(SL* pc)
{
    assert(pc);
    
    free(pc->a);
    pc->a == NULL;
    pc->size = pc->capacity = 0;
}

void SLPrint(SL* pc)
{
    assert(pc);

    for (int i = 0; i < pc->size; ++i)
    {
        printf("%d ", pc->a[i]);
    }
    printf("\n");
}

void SLCheckCapacity(SL* pc)
{
    assert(pc);

    if (pc->size == pc->capacity)
    {
        SLDataType* tmp = (SLDataType*)realloc(pc->a, sizeof(SLDataType) * pc->capacity * 2);
        if (NULL == tmp)
        {
            perror("realloc fail");
            return;
        }
        
        pc->a = tmp;
        pc->capacity *= 2;
    }
}

void SLPushBack(SL* pc, SLDataType x)
{
    assert(pc);

    SLCheckCapacity(pc);
    pc->a[pc->size++] = x;
}

void SLPopBack(SL* pc)
{
    assert(pc);
    assert(pc->size > 0);

    --pc->size;
}

void SLPushFront(SL* pc, SLDataType x)
{
    assert(pc);

    SLCheckCapacity(pc);
    int end = pc->size - 1;
    while (end >= 0)
    {
        pc->a[end + 1] = pc->a[end];
        --end;
    }

    pc->a[0] = x;
    ++pc->size;
}

void SLPopFront(SL* pc)
{
    assert(pc);
    assert(pc->size > 0);

    int begin = 1;
    while (begin < pc->size)
    {
        pc->a[begin - 1] = pc->a[begin];
        ++begin;
    }
    --pc->size;
}

int SLFind(SL* pc, SLDataType x)
{
    assert(pc);

    for (int i = 0; i < pc->size; ++i)
    {
        if(x == pc->a[i])
        {
            return i;
        }
    }
    return -1;
}

void SLInsert(SL* pc, int pos, SLDataType x)
{
    assert(pc);
    assert(pos >= 0 && pos <= pc->size);

    SLCheckCapacity(pc);
    int end = pc->size - 1;
    while (end >= pos)
    {
        pc->a[end + 1] == pc->a[end];
        --end;
    }

    pc->a[pos] == x;
    ++pc->size;
}

void SLErase(SL* pc, int pos)
{
    assert(pc);
    assert(pc->size > 0);

    int begin = pos + 1;
    while (begin < pc->size)
    {
        pc->a[begin - 1] = pc->a[begin];
        ++begin;
    }
    
    ++pc->size;
}